import { Link,useLocation }from "react-router-dom"
import { Menu} from 'antd';
import menuList from "../../config/menuList.js"
import "./index.less";

const { SubMenu } = Menu;

export default function Index() {
  // 动态生成左侧的菜单
  let pathName=useLocation().pathname //获取location中的pathName
  // 定义二次菜单打开项
  let openKey=""
  // 该函数用来生成左侧菜单
  const getMenuNode=(menuList)=>{
    return menuList.map( item =>{
      if(!item.children){
        return (
          <Menu.Item key={item.key} >
            <Link to={item.key}>{item.title}</Link>
          </Menu.Item>
        )
      }else{
        let cItem = item.children.find(cItem=>cItem.key===pathName)
        if( cItem ){
          openKey = item.key
        }
        return(
          <SubMenu key={item.key} title={item.title}>
            {
              getMenuNode(item.children)
            }
          </SubMenu>
        )
      }
    })
  }
  // 先调用该函数用来生成菜单项，否则获取不到openKey值
  const menuNodes = getMenuNode(menuList)

  return (
    <div className='left_nav'>
      <Link to="/main/home" className='left_nav_header'>
        <img src={require("../../assets/images/logo1.png")} alt="" />
        <h1>后台管理</h1>
      </Link>
      <Menu
        mode="inline"
        theme="dark"
        selectedKeys={[pathName]}
        defaultOpenKeys={[openKey]}
      >
        { menuNodes }
      </Menu>
    </div>
  )
}
